#encoding=utf-8
'''
Created on 2013-2-20

@author: Administrator
'''
from actionModule.handle import base
import json
from base.common import retSuccess, execMysql
from config.db.models import Project, Table
import os
from actionModule.htmlHandle import htmlHandle

prefix='/src'
common='private static int __seq__=1;\n public synchronized static int __getSeq__() {\n'
common+='return __seq__++;\n'
common+='}\n'
common+='public synchronized static void __setSeq__(int uq) {\n'
common+='__seq__=uq;\n}'

commonImport=""
rowStr="\n"
fieldType='public'

def getPackage(bean):
    arr=[]
    arr.append("package ")
    arr.append(bean['package'].replace("/","."))
    arr.append(";")
    arr.append(commonImport)
    arr.append(rowStr)
    arr.append("public class "+bean['name']+" {")
    arr.append(rowStr)
    return "".join(arr)


def getFilePath(str):
    arr=str.split(".")
    ret=[]
    for i in arr:
        ret.append(i)
        
    return "/".join(ret)

def createBean(bean,pro):
    beanPath=pro['path']+prefix
    try:
        os.makedirs(beanPath+"/"+bean['package'])
    except Exception:
        pass
    beanPath=beanPath+"/"+bean['package']+"/"+bean['name']+"."+pro["type"]
    
    #备份旧文件
    try:
        beanFile=open(beanPath,"rb")
        backFile=open(beanPath+"_back","wb")
        backFile.write(beanFile.read())
        backFile.close()
        beanFile.close()
    except Exception:
        pass
        
    beanFile=open(beanPath,"wb")
    
    beanFile.write(getPackage(bean))
    if isinstance(bean['fields'],basestring):
        fields=json.loads(bean['fields'])
    else:
        fields=bean['fields']
    content=[]
    for item in fields:
        type=fields[item]
        if type=="":
            type='String'
        content.append(fieldType)
        content.append(type)
        content.append(item+";"+rowStr)
    
    content.append(common)
    content.append(rowStr+"}")
    beanFile.write(" ".join(content))
    beanFile.close
    
    
def getFieldName(arr):
    ret=""
    for item in arr:
        ret+=item.capitalize();
    return ret;

class relaBean(base):
    def qryRela(self):
        projectId=self.getPost("id")
        sql=[]
        sql.append("select b.id,b.name from db_relabean a,db_table b,db_project c ")
        sql.append("where b.id=a.bean_id and c.id=a.project_id ")
        sql.append("and a.project_id= ")
        sql.append(projectId)
        return execMysql("".join(sql))
        
    def saveRela(self):
        projectId=self.getPost("id")
        self.table.objects.filter(project_id=projectId).delete()
        forms=self.getPost("forms")
        forms=json.loads(forms)
        for item in forms:
            temp=self.table()
            temp.bean_id=item
            temp.project_id=projectId
            temp.save()
        return retSuccess("保存成功")
    
    def createFile(self):
        proId=self.getPost("id") 
        beanId=self.getPost("beanId")
        pro=Project.objects.get(id=proId)
        bean=Table.objects.get(id=beanId)
        bean.setAttr("package",getFilePath(bean['package']))
        createBean(bean,pro)
        return retSuccess("创建成功")
    
    def createBatchFile(self):
        proId=self.getPost("id") 
        sql=[]
        sql.append("select b.* from db_relabean a,db_table b,db_project c ")
        sql.append("where b.id=a.bean_id and c.id=a.project_id ")
        sql.append("and a.project_id= ")
        sql.append(proId)
        beans=execMysql("".join(sql))
        pro=Project.objects.get(id=proId)
        for item in beans:
            item["package"]=getFilePath(item["package"])
            createBean(item,pro)
            
        return retSuccess("创建成功")    
                                                                           
    def syncDbBean(self):
        name=self.getPost("name")
        field=json.loads(self.getPost("field"))
        arr=name.split("_")
        pro=Project.objects.get(id=self.getPost("id"))
        item={}
        item['package']="db/bean"
        item['fields']=field[0]
        item['name']=getFieldName(arr)
        createBean(item,pro)
        htmlHandle().createJson(item['name'],field[1])
        return retSuccess("创建成功:"+item['name'])  
        